package com.sxf.biz.ocr.service;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * @projectName: basicinfo
 * @package: com.ccccit.basicinfo.server.utils
 * @className: FileCompressUtil
 * @author: guolei
 * @date: 2020/12/25 15:47
 * @description:
 */
public class FileCompressUtil {

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0");

    public static String encodingCompress(String content,Long fileAvailabel) throws IOException {
        String result = "";
        byte[] byteArray = ImageEncodingUtils.decod(content);
        Long fileSize = Long.valueOf(byteArray.length);
        if (fileSize.compareTo(fileAvailabel) > 0) {
            Double scale = Double.valueOf(DECIMAL_FORMAT.format((double) fileAvailabel / fileSize));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Thumbnails.of(new ByteArrayInputStream(byteArray)).scale(scale).toOutputStream(baos);
            result = ImageEncodingUtils.encodingImage(baos.toByteArray());
        }else{
            result = content;
        }
        return result;
    }

    public static byte[] fileCompress(MultipartFile multipartFile,Long fileAvailabel) throws IOException {
        byte[] byteArray = null;
        Long fileSize = multipartFile.getSize();
        if (fileSize.compareTo(fileAvailabel) > 0) {
            Double scale = Double.valueOf(DECIMAL_FORMAT.format((double) fileAvailabel / fileSize));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Thumbnails.of(multipartFile.getInputStream()).scale(scale).toOutputStream(baos);
            byteArray = baos.toByteArray();
        } else {
            byteArray = multipartFile.getBytes();
        }
        return byteArray;
    }

    public static byte[] bytesCompress(byte[] byteArray,Long fileAvailabel) throws IOException {
        Long fileSize = Long.valueOf(byteArray.length);
        if (fileSize.compareTo(fileAvailabel) > 0) {
            Double scale = Double.valueOf(DECIMAL_FORMAT.format((double) fileAvailabel / fileSize));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Thumbnails.of(new ByteArrayInputStream(byteArray)).scale(scale).toOutputStream(baos);
            byteArray = baos.toByteArray();
        }
        return byteArray;
    }
}
